import React from 'react';
import Flex from '../Flex/Flex';
import { StyledTextfield, HintMessage, StyledTextfieldContainer } from './Textfield.styled';
import { TTextfieldProps } from './Textfield.types';
import { ChildrenContainer } from './ChildrenContainer.styled';
import { ReactComponent as VisibilityIcon } from '../../../images/visibility.svg';
import { ReactComponent as VisibilityOffIcon } from '../../../images/visibility_off.svg';

/**
 * @function Textfield - Компонент ввода.
 * @param {TTextfieldProps} props - Свойства компонента ввода.
 * @param ref - Ссылка на компонент ввода.
 * @return {React.Element} - Компонент ввода.
 */
const Textfield = React.forwardRef<HTMLInputElement, TTextfieldProps>((
  {
    type,
    hint,
    clearClick,
    icon,
    dimension,
    status,
    ...nextProps
    
  }, ref) => {

  const [showPassword, setShowPassword] = React.useState<boolean>(false);

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  return (
    <StyledTextfieldContainer dimension={dimension}>
      <StyledTextfield 
        ref={ref} 
        type={type === 'password' && showPassword ? 'text' : type}
        status={status} 
        dimension={dimension} 
        {...nextProps} 
      />

      {icon && (
        <ChildrenContainer dimension={dimension} onClick={clearClick}>
          {icon}
        </ChildrenContainer>
      )}

      {hint && (
        <HintMessage hint={hint} status={status}>
          {hint}
        </HintMessage>
      )}
      {type === 'password' && (
        <ChildrenContainer dimension={dimension} onClick={togglePasswordVisibility}>
          {showPassword && <VisibilityIcon />}
          {!showPassword && <VisibilityOffIcon />}
        </ChildrenContainer>
      )}
    </StyledTextfieldContainer>
  );
});

Textfield.defaultProps = {
  type: 'text',
};

Textfield.displayName = 'Input';

export default Textfield;
